import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/components/Layout/index.vue'

/**
 * 智慧医疗管理系统路由配置
 * 采用嵌套路由结构，主布局包含子页面
 */
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/dashboard'
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/auth/Login.vue'),
      meta: {
        title: '登录',
        requiresAuth: false
      }
    },
    {
      path: '/',
      component: Layout,
      redirect: '/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('@/views/dashboard/index.vue'),
          meta: {
            title: '仪表盘',
            requiresAuth: true
          }
        },
        {
          path: 'content',
          name: 'Content',
          redirect: '/content/carousel',
          meta: {
            title: '内容管理',
            requiresAuth: true
          },
          children: [
            // 科室管理路由 - 重定向到默认医院的科室管理
            {
              path: 'department',
              name: 'GlobalDepartmentManagement',
              redirect: '/content/hospital/1/departments',
              meta: {
                title: '科室管理',
                requiresAuth: true
              }
            },
            {
              path: 'carousel',
              name: 'CarouselManagement',
              component: () => import('@/views/content/CarouselManagement.vue'),
              meta: {
                title: '轮播图管理',
                requiresAuth: true
              }
            },
            {
              path: 'carousel/add',
              name: 'CarouselAdd',
              component: () => import('@/views/content/CarouselAdd.vue'),
              meta: {
                title: '新增轮播图',
                requiresAuth: true
              }
            },
            {
              path: 'carousel/edit/:id',
              name: 'CarouselEdit',
              component: () => import('@/views/content/CarouselEdit.vue'),
              meta: {
                title: '编辑轮播图',
                requiresAuth: true
              }
            },
            {
              path: 'hospital',
              name: 'HospitalManagement',
              component: () => import('@/views/hospital/HospitalManagement.vue'),
              meta: {
                title: '医院管理',
                requiresAuth: true
              }
            },
            {
              path: 'hospital/add',
              name: 'HospitalAdd',
              component: () => import('@/views/hospital/AddHospital.vue'),
              meta: {
                title: '新增医院',
                requiresAuth: true
              }
            },
            {
              path: 'hospital/edit/:id',
              name: 'HospitalEdit',
              component: () => import('@/views/hospital/AddHospital.vue'),
              meta: {
                title: '编辑医院',
                requiresAuth: true
              }
            },
            {
              path: 'hospital/detail/:id',
              name: 'HospitalDetail',
              component: () => import('@/views/hospital/HospitalDetail.vue'),
              meta: {
                title: '医院详情',
                requiresAuth: true
              }
            },
            {
              path: 'hospital/:hospitalId/departments',
              name: 'DepartmentManagement',
              component: () => import('@/views/hospital/HospitalDepartmentManagement.vue'),
              meta: {
                title: '科室管理',
                requiresAuth: true
              }
            },
            {
              path: 'hospital/:hospitalId/department/add',
              name: 'DepartmentAdd',
              component: () => import('@/views/hospital/DepartmentEdit.vue'),
              meta: {
                title: '新增科室',
                requiresAuth: true
              }
            },
            {
              path: 'hospital/:hospitalId/department/edit/:id',
              name: 'DepartmentEdit',
              component: () => import('@/views/hospital/DepartmentEdit.vue'),
              meta: {
                title: '编辑科室',
                requiresAuth: true
              }
            },
            {
              path: 'hospital/:hospitalId/department/:id',
              name: 'DepartmentDetail',
              component: () => import('@/views/hospital/DepartmentDetail.vue'),
              meta: {
                title: '科室详情',
                requiresAuth: true
              }
            }
          ]
        },
        {
          path: 'system',
          name: 'System',
          redirect: '/system/users',
          meta: {
            title: '系统管理',
            requiresAuth: true
          },
          children: [
            {
              path: 'users',
              name: 'UserManagement',
              component: () => import('@/views/system/UserManagement.vue'),
              meta: {
                title: '用户管理',
                requiresAuth: true
              }
            },
            {
              path: 'roles',
              name: 'RoleManagement',
              component: () => import('@/views/system/RoleManagement.vue'),
              meta: {
                title: '角色管理',
                requiresAuth: true
              }
            }
          ]
        }
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/views/error/404.vue'),
      meta: {
        title: '页面不存在'
      }
    }
  ]
})

/**
 * 路由守卫 - 权限验证
 * 检查用户登录状态，保护需要认证的页面
 */
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta?.title) {
    document.title = `${to.meta.title} - 智慧医疗管理系统`
  }

  // 检查是否需要登录权限
  const requiresAuth = to.matched.some(record => record.meta?.requiresAuth)
  
  // 检查用户是否已登录
  const token = localStorage.getItem('admin_token')
  const isLoggedIn = !!token
  
  if (requiresAuth && !isLoggedIn) {
    // 需要登录但未登录，重定向到登录页
    next({
      path: '/login',
      query: { redirect: to.fullPath } // 记录原始路径，登录后跳转回去
    })
  } else if (to.path === '/login' && isLoggedIn) {
    // 已登录用户访问登录页，重定向到仪表盘
    next('/dashboard')
  } else {
    // 正常访问
    next()
  }
})

/**
 * 路由错误处理
 */
router.onError((error) => {
  console.error('路由错误:', error)
})

export default router
